<!-- components/ui/AttractionDetailDialog.vue -->
<template>
  <div v-if="modelValue" class="fixed inset-0 z-50 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
      <!-- 背景遮罩 -->
      <div 
        class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75" 
        @click="$emit('update:modelValue', false)"
      ></div>

      <!-- 弹窗内容 -->
      <div class="inline-block w-full max-w-4xl p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white shadow-xl rounded-2xl">
        <!-- 头部 -->
        <div class="flex justify-between items-start mb-6">
          <div>
            <h2 class="text-3xl font-bold mb-2">{{ attraction.name }}</h2>
            <div class="flex items-center">
              <div class="text-yellow-400 mr-2">
                <font-awesome-icon 
                  v-for="star in fullStars"
                  :key="'full-' + star"
                  icon="star"
                />
                <font-awesome-icon 
                  v-if="hasHalfStar"
                  icon="star-half-alt"
                />
                <font-awesome-icon
                  v-for="star in emptyStars"
                  :key="'empty-' + star"
                  :icon="['far', 'star']"
                />
              </div>
              <span class="text-gray-600">({{ attraction.reviews || 0 }}条评价)</span>
            </div>
          </div>
          <div class="flex items-center gap-4">
            <span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm">
              {{ attraction.category }}
            </span>
            <button 
              @click="$emit('update:modelValue', false)" 
              class="text-gray-400 hover:text-gray-500"
            >
              <font-awesome-icon icon="times" class="text-xl" />
            </button>
          </div>
        </div>

        <!-- 主体内容 -->
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
          <!-- 左侧图片+缩略图+地图 -->
          <div class="lg:col-span-7 flex flex-col gap-4">
            <!-- 主图 -->
            <div class="h-80 bg-gray-100 rounded-xl overflow-hidden">
              <img 
                :src="currentImage" 
                :alt="attraction.name"
                class="w-full h-full object-cover"
              />
            </div>
            <!-- 缩略图 -->
            <div class="grid grid-cols-4 gap-2">
              <div 
                v-for="(img, index) in attraction.images"
                :key="index"
                @click="currentImageIndex = index"
                class="h-16 cursor-pointer rounded-lg overflow-hidden"
                :class="{'ring-2 ring-blue-500': currentImageIndex === index}"
              >
                <img 
                  :src="img" 
                  class="w-full h-full object-cover"
                />
              </div>
            </div>
            <!-- 地图预览（左下角） -->
            <div class="rounded-xl overflow-hidden mt-2">
              <div 
                id="attraction-map" 
                ref="mapContainer"
                class="w-full h-48" 
                style="min-height: 300px;"
              ></div>
            </div>
          </div>

          <!-- 右侧信息区 -->
          <div class="lg:col-span-5 flex flex-col gap-6">
            <!-- 基本信息 -->
            <div class="bg-blue-50 rounded-xl p-4">
              <h3 class="font-semibold mb-3">基本信息</h3>
              <div class="space-y-2 text-gray-700">
                <p><font-awesome-icon :icon="['fas', 'clock']" class="mr-2 w-5" />{{ attraction.hours }}</p>
                <p><font-awesome-icon :icon="['fas', 'ticket']" class="mr-2 w-5" />{{ attraction.tickets }}</p>
                <p><font-awesome-icon :icon="['fas', 'location-dot']" class="mr-2 w-5" />{{ attraction.address }}</p>
              </div>
            </div>

            <!-- 联系方式 -->
            <div v-if="attraction.contact" class="bg-blue-50 rounded-xl p-4">
              <h3 class="font-semibold mb-3">联系方式</h3>
              <div class="space-y-2 text-gray-700">
                <p><font-awesome-icon :icon="['fas', 'phone']" class="mr-2 w-5" />{{ attraction.contact.phone }}</p>
                <p><font-awesome-icon :icon="['fas', 'envelope']" class="mr-2 w-5" />{{ attraction.contact.email }}</p>
                <p><font-awesome-icon :icon="['fas', 'globe']" class="mr-2 w-5" />{{ attraction.contact.website }}</p>
              </div>
            </div>

            <!-- 游览提示 -->
            <div v-if="attraction.tips" class="bg-blue-50 rounded-xl p-4">
              <h3 class="font-semibold mb-3">游览提示</h3>
              <ul class="space-y-2 text-gray-700">
                <li v-for="(tip, index) in attraction.tips" :key="index" class="flex items-start">
                  <font-awesome-icon :icon="['fas', 'lightbulb']" class="mr-2 w-5 mt-1 text-yellow-500" />
                  <span>{{ tip }}</span>
                </li>
              </ul>
            </div>

            <!-- 景点介绍 -->
            <div class="bg-white rounded-xl p-4">
              <h3 class="text-xl font-semibold mb-4">景点介绍</h3>
              <p class="text-gray-700">{{ attraction.description }}</p>
            </div>

            <!-- 操作按钮 -->
            <div class="space-y-3">
              <button class="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700">
                <font-awesome-icon :icon="['fas', 'directions']" class="mr-2" />查看位置
              </button>
              <button class="w-full border border-blue-600 text-blue-600 py-3 rounded-lg hover:bg-blue-50">
                <font-awesome-icon :icon="['fas', 'heart']" class="mr-2" />收藏景点
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

// 高德地图配置
const AMAP_CONFIG = {
  key: '512cb9e9902a4d511b7abfc6f55d5ac9', // 替换为你的实际密钥
  securityJsCode: '1f3bf84f8f340e84dfc49e5d5dcebcbe', // 替换为你的实际安全密钥
}

// 定义更完整的类型
interface Attraction {
  id: number
  name: string
  category: string
  rating: number
  reviews?: number
  description: string
  images?: string[]
  image: string
  hours?: string
  tickets?: string
  address?: string
  location?: {
    longitude: number
    latitude: number
  }
  contact?: {
    phone: string
    email: string
    website: string
  }
  tips?: string[]
}

const props = defineProps<{
  modelValue: boolean
  attraction: Attraction
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

// 图片切换逻辑
const currentImageIndex = ref(0)
const currentImage = computed(() => {
  if (!props.attraction.images?.length) {
    return props.attraction.image
  }
  return props.attraction.images[currentImageIndex.value]
})

// 星级评分计算
const fullStars = computed(() => Math.floor(props.attraction.rating))
const hasHalfStar = computed(() => props.attraction.rating % 1 >= 0.5)
const emptyStars = computed(() => 5 - Math.ceil(props.attraction.rating))

// 地图相关
const mapContainer = ref<HTMLElement | null>(null)
const map = ref<any>(null)
const marker = ref<any>(null)

// 修改地图初始化函数
const initMap = async () => {
  if (!mapContainer.value || !props.attraction.location) {
    console.warn('地图容器或位置信息不存在')
    return
  }

  try {
    // 检查是否已经初始化过地图
    if (map.value) {
      map.value.destroy()
      map.value = null
    }
  //解决地图加载失败的问题
  AMapLoader.reset()

    const AMap = await AMapLoader.load({
      key: AMAP_CONFIG.key,
      version: '2.0',
      plugins: ['AMap.Scale', 'AMap.ToolBar'],
      // 注意：这里不需要传入 securityJsCode
    })

    const position = [
      props.attraction.location.longitude,
      props.attraction.location.latitude
    ]

    // 创建地图实例
    map.value = new AMap.Map(mapContainer.value, {
      zoom: 15,
      center: position,
      viewMode: '2D', // 设置地图模式
    })

    // 创建标记点
    marker.value = new AMap.Marker({
      position: position,
      title: props.attraction.name,
    })

    map.value.add(marker.value)

    // 添加地图控件
    map.value.addControl(new AMap.Scale())
    map.value.addControl(new AMap.ToolBar())

  } catch (error) {
    console.error('地图加载失败:', error)
  }
}

// 优化监听逻辑
watch(
  () => props.modelValue,
  async (newVal) => {
    if (newVal && props.attraction.location) {
      await nextTick()
      initMap()
    }
  }
)

// 优化组件卸载时的清理
onUnmounted(() => {
  if (map.value) {
    map.value.destroy()
    map.value = null
  }
  if (marker.value) {
    marker.value = null
  }
})
</script>

<style scoped>
#attraction-map {
  width: 100%;
  min-height: 180px;
  height: 180px;
  background-color: #f5f5f5;
}
</style>